/**
 * 只能在可见区域内拖动才有效。特别是在firefox中的可见高度是元素填充body的高度。如果
 * 仅仅$("body")绑定的话不会出现虚线框。其其他浏览器下不会出现此类情况。
 * 只要在firefox浏览器下加了元素方可自动出现.
 * 支持 ie6,7,8,9 google firefox
 *
 *
 * 修改版  for 海外
 * @param {Object} $
 * @memberOf {TypeName} 
 * @return {TypeName} 
 */
(function($){
    function stopBubble(e) {
        //如果提供了事件对象，则这是一个非IE浏览器
        if (e && e.stopPropagation){
            //因此它支持W3C的stopPropagation()方法
            e.stopPropagation();
        }else{
            //否则，我们需要使用IE的方式来取消事件冒泡
            if(window.event)
                window.event.cancelBubble = true;
        }
    }


    function getClientHeight() {
        // var clientHeight = 0;
        // if (document.body.clientHeight && document.documentElement.clientHeight) {
        //     var clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight
        //         : document.documentElement.clientHeight;
        // } else {
        //     var clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight
        //         : document.documentElement.clientHeight;
        // }
        // return clientHeight;
        return $(window).height();
    }


    function doCreateProcess() {
        var divContent = createContainerDiv();

        //paint
        $("body").append(divContent);

        //paint pic
        //css control
        $("#tm-box-imgs").css({height:0,width:0});


        //request
        tmImgBoxLoading(curArr[curIdx].url,opts);


        $("#tm-box-wrap").width(opts.width);
        $("#tm-box-content").width(opts.width-20).height(opts.height);
        var vheight = $(window).height();
        if(document.body.scrollHeight>$(window).height()){
            vheight = document.body.scrollHeight-20;
        }
        $(".tm-ui-overdisplay").height(vheight);


        //bind shadow close events
        // $(".tm-ui-overdisplay").click(function(){
        //     $("#tm-box-loading").remove();
        //     $("#tm-box-wrap").fadeIn("fast",function(){
        //         $(this).remove();
        //     });
        //     $(".tm-ui-overdisplay").fadeIn("fast",function(){
        //         $(this).remove();
        //     });
        // });

        //position
        //close event
        $.tmImgbox.methods.resizeImgbox();

        if(isNotEmpty(opts.top)){
            $("#tm-box-wrap").css("top",opts.top);
        }

        /*翻页控制*/
        var index = curIdx;
        var imgArr = curArr;
        $("#tm-box-left").click(function(){
            if(index==0)
                index = imgArr.length;
            index--;

            //request
            tmImgBoxLoading(imgArr[index].url,opts,1);
        });

        $("#tm-box-right").click(function(){
            index++;
            if(index== imgArr.length)
                index = 0;

            //request
            tmImgBoxLoading(imgArr[index].url,opts);
        });
        /*翻页控制*/

    }

    function createContainerDiv() {
        var ret = '<div class="tm-ui-overdisplay" ></div><div id="tm-box-wrap" style="display: block;  height: 468px;">'+
            '<div id="tm-box-outer">'+
            '<div class="tm-box-bg" id="tm-box-bg-n"></div>'+
            '<div class="tm-box-bg" id="tm-box-bg-ne"></div>'+
            '<div class="tm-box-bg" id="tm-box-bg-e"></div>'+
            '<div class="tm-box-bg" id="tm-box-bg-se"></div>'+
            '<div class="tm-box-bg" id="tm-box-bg-s"></div>'+
            '<div class="tm-box-bg" id="tm-box-bg-sw"></div>'+
            '<div class="tm-box-bg" id="tm-box-bg-w"></div>'+
            '<div class="tm-box-bg" id="tm-box-bg-nw"></div>'+
            '<div id="tm-box-content">'+
            '<img id="tm-box-imgs"  title="'+curArr[curIdx].name+'"/>'+
            '</div>'+
            '<a id="tm-box-close" style="display: inline;"></a>'+
            // '<div id="tm-box-title" style=""><span id="tm-box-tit">'+title+'</span><span id="tm-box-timer" style="margin:5px;"><a href="javascript:void(0)" id="tm-auto-play">'+zLocale.GLOBAL__AUTO_PLAY+'</a></span></div>' +
            '<a href="javascript:;" id="tm-box-left" style="display: block;"><span class="tm-box-ico" id="tm-box-left-ico"></span></a>'+
            '<a href="javascript:;" id="tm-box-right" style="display: block;"><span class="tm-box-ico" id="tm-box-right-ico"></span></a>'+
            '</div>'+
            '</div>';

        return ret;
    }

    function refreshSrc() {
        curArr = opts.src();
    }

    function setCurrentIdxByPicId(pid) {
        refreshSrc();
        for (var i = 0; i < curArr.length; i++) {
            var obj = curArr[i];
            if(obj.id==pid){
                curIdx =i;
                break;
            }
        }
    }

    var opts;
    var curIdx=0;
    var curArr=[];

    //1.param id
    //2.param {}
    $.tmImgbox = function(options){

        if ( typeof options === 'object') {
            console.log('init tmImgbox...');
            opts = $.extend({},$.tmImgbox.defaults,options);
            console.log(opts);

        } else {
            var paramId = options;

            refreshSrc();
            console.log(curIdx);
            // console.log(curArr);

            //
            setCurrentIdxByPicId(paramId);

            //
            doCreateProcess();

        }

    }


	function tmImgBoxLoading(src,opts,dtype){
		var img = new Image();
		img.src = src;
		if(img.complete){
			tmImgBoxLoadingProxy(img,opts,dtype);
		}else{
			img.onreadystatechange = function () {
			}
			img.onload = function () {
				tmImgBoxLoadingProxy(img,opts,dtype);
			}
			img.onerror = function () {
				//alert("图片加载失败...");
				if(dtype==1){
					$("#tm-box-left").click();
				}else{
					$("#tm-box-right").click();
				}
			}
		}
	};
	
	function tmImgBoxLoadingProxy(img,opts){
		$("#tm-box-loading").remove();
		var top = (getClientHeight() - opts.height) / 2;
        top = top < 0?0:top;
		$("#tm-box-wrap").append('<div id="tm-box-loading" style="display:none; "><div style="top: -80px; "></div></div>');	
		var title = $("img[src='"+img.src+"']").attr("title")
		if(isEmpty(title)){
			title = $("*[_src='"+img.src+"']").attr("title");
		}
		$("#tm-box-loading").fadeIn(200,function(){
			$(this).hide();
			$("#tm-box-imgs").attr("src",img.src);
			$("#tm-box-tit").html(title);
			var width = img.width;
			var height = img.height;
			var bodyWidth = opts.width;
			var bodyHeight = opts.height;
			var box = $.tmImgbox.methods.resizeImg(img,760,550);
			$("#tm-box-imgs").width(box.width).height(box.height);
			var width = $("#tm-box-imgs").width();
			var height = $("#tm-box-imgs").height();
			var left = (bodyWidth - width)/2-10;
			var top = (bodyHeight - height)/2 ;
			$("#tm-box-imgs").css({left:left,top:top});
		});
	}
	

	$.tmImgbox.methods = {
		loadImg : function(src,$img){
		      var o= new Image();
		      o.src = src;
		      if(o.complete){
		    	  $("#tm-box-loading").remove();
		    	  $img.attr("src",src);
		    	  $img.show();
		      }else{
		        o.onload = function(){
		          $("#tm-box-loading").remove();
		          $img.attr("src",src);
		          $img.show();
		        };
		        o.onerror = function(){
		        	//myHomeInitLoading("图片加载失败")
		        };
		    }
		},
		
		resizeImg:function (img,iwidth,iheight){ 
		    var image= img;  
		    var boxWH = {};
		    if(image.width>0 && image.height>0){
		     	boxWH.width=image.width;
		     	boxWH.height=image.height;	    
		        if(boxWH.width>iwidth){    
		          	boxWH.height = (boxWH.height*iwidth)/boxWH.width;  
		            boxWH.width = iwidth;
		                 
		        }
		        if(boxWH.height>iheight){    
		          	boxWH.width = (boxWH.width*iheight)/boxWH.height;;   
		            boxWH.height = iheight;	             	 
		         }    	           
		    }   
		    return boxWH;
		} ,
		
		resizeImgbox:function(){
			// var bodyWidth = $(window).innerWidth() ;
			var bodyWidth = $(window).width();
			var bodyHeight = getClientHeight();
			var width = $("#tm-box-wrap").width();
			var height = $("#tm-box-wrap").height();
			var left = (bodyWidth - width)/2;
			var top = (bodyHeight - height)/2 - 30;
            left = left < 0?0:left;
            top = top < 0?0:top;
			$("#tm-box-wrap").css({left:left,top:top});

			$("#tm-box-close").click(function(){
				$("#tm-box-wrap").fadeOut('fast',function(){
					$(this).remove();
				});
					
				$(".tm-ui-overdisplay").fadeIn("fast",function(){
					$(this).remove();
				});
			});
		}
	}
	
	
	$.tmImgbox.defaults ={
		imgArrs:[],
		imgClassName:'', //预览图片
		drag:false,
		width:760,
		height:420,
		eventType:"click",
		time:2,
		callback:function(){
			
		}
	}
})(jQuery)
